package com.snowflake.ecatalog.util;

import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.shiro.SecurityUtils;
import org.springframework.web.util.WebUtils;

import com.snowflake.ecatalog.entity.Profile;
import com.snowflake.ecatalog.entity.User;
import com.snowflake.ecatalog.service.account.ShiroDbRealm.ShiroUser;

/**
 * 登陆信息工具类
 * 
 */
public class LoginUtil {
	/**
	 * 取出Shiro中的当前用户.
	 */
	public static User getCurrentUser() {
		ShiroUser user = (ShiroUser) SecurityUtils.getSubject().getPrincipal();
		return new User(user.id);
	}

	/**
	 * 取出Shiro中的当前用户Id.
	 */
	public static Long getCurrentUserId() {
		ShiroUser user = (ShiroUser) SecurityUtils.getSubject().getPrincipal();
		return user.id;
	}

	/**
	 * 更新Shiro中当前用户的用户名.
	 */
	public static void updateCurrentUserName(String userName) {
		ShiroUser user = (ShiroUser) SecurityUtils.getSubject().getPrincipal();
		user.name = userName;
	}

	/**
	 * 从session中获取profileId
	 */
	public static Long getProfileIdFromSession(HttpSession session) {
		return (Long) session.getAttribute("PROFILE_ID");
	}

	/**
	 * 从session中获取profileId
	 */
	public static Long getProfileIdFromRequest(ServletRequest request) {
		return (Long) WebUtils.getRequiredSessionAttribute((HttpServletRequest) request, "PROFILE_ID");
	}

	/**
	 * 从session中获取profile对象
	 */
	public static Profile getProfileFromRequest(ServletRequest request) {
		Long profileId = getProfileIdFromRequest(request);
		return new Profile(profileId);
	}
}
